import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import 'package:get/get.dart';
import 'package:like_button/like_button.dart';
import 'package:live_music/components/feedback/PageFeedBack.dart';
import 'package:live_music/components/ui/theme.dart';
import 'package:live_music/event/momonEvent.dart';
import 'package:live_music/models/comment_detail_model.dart';
import 'package:live_music/models/moment_detail_model.dart';
import 'package:live_music/pages/comment/comment_detail.dart';
import 'package:live_music/pages/publish/widget/frinend_list_select_publish.dart';
import 'package:live_music/services/commentService.dart';
import 'package:live_music/services/operationServiece.dart';
import 'package:live_music/utils/cgq_utils.dart';
import 'package:live_music/utils/colors.dart';
import 'package:live_music/utils/commentParse.dart';
import 'package:live_music/utils/eventBusUtils.dart';
import 'package:live_music/utils/screen_utils.dart';
import 'package:live_music/utils/sp_utils.dart';
import 'package:live_music/utils/toast_utils.dart';
import 'package:live_music/utils/util.dart';

///视频评论部件
class VideoCommentWidget extends StatefulWidget {
  const VideoCommentWidget({Key key, this.momentDetailData}) : super(key: key);
  final MomentDetailModel momentDetailData;
  @override
  _VideoCommentWidgetState createState() {
    return _VideoCommentWidgetState();
  }
}

class _VideoCommentWidgetState extends State<VideoCommentWidget>
    with WidgetsBindingObserver {
  EasyRefreshController _easyRefreshController;
  // 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController _scrollController;
  // 列表数组模型
  List<CommentDetailModel> _commentListModel;
  int pageNo = 1;
  int pageSize = 20;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String errorMsg;
  MomentDetailModel momentDetailData;
  TextEditingController _commentEditController;
  CommentDetailModel parentComment;
  FocusNode _focusNode = FocusNode();
  bool isShowkeyborad = false;
  bool disabledPublish = true;
  List options = ['删除'];
  final ScrollController controller = ScrollController();
  void initState() {
    super.initState();
    _commentEditController = TextEditingController();
    _easyRefreshController = EasyRefreshController();
    _scrollController = ScrollController();
    EventBusUtils.getInstance().on<SelectFriendPublishEvent>().listen((event) {
      setState(() {
        _commentEditController.text =
            _commentEditController.text + event.name + " ";
      });
    });
    setState(() {
      momentDetailData = widget.momentDetailData;
    });
    getData();
    WidgetsBinding.instance?.addObserver(this);
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      setState(() {
        if (MediaQuery.of(context).viewInsets.bottom == 0) {
          //关闭键盘
          isShowkeyborad = false;
        } else {
          //显示键盘
          isShowkeyborad = true;
        }
      });
    });
  }

  @override
  void dispose() {
    _easyRefreshController.dispose();
    _scrollController.dispose();
    WidgetsBinding.instance?.removeObserver(this);
    super.dispose();
  }

  getData({bool replace = true}) async {
    try {
      Map<String, dynamic> data = {
        "pageNo": pageNo,
        "pageSize": pageSize,
        "momentId": momentDetailData.id,
        "parentId": 0
      };
      Map<String, dynamic> result =
          await CommentService.queryMomentComment(data);
      List<dynamic> momentList = result['body'];
      CommentListModel momentListModel = CommentListModel.fromJson(momentList);
      setState(() {
        pageNo++;
        hasMore = pageSize == momentListModel.list.length;
        if (replace) {
          _commentListModel = momentListModel.list;
        } else {
          _commentListModel.addAll(momentListModel.list);
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  // 刷新回调(null为不开启刷新)
  Future _onRefresh() async {
    setState(() {
      pageNo = 1;
    });
    await getData(replace: true);
    if (error) {
      setState(() => error = false);
    }
    // 恢复刷新状态 使onLoad再次可用
    _easyRefreshController.resetLoadState();
  }

  // 加载回调(null为不开启加载)
  Future _onLoad() async {
    if (hasMore) {
      await getData(replace: false);
    }
    // // 结束加载
    await Future.delayed(const Duration(seconds: 0), () {
      _easyRefreshController.finishLoad(success: true, noMore: !hasMore);
    });
  }

  @override
  Widget build(BuildContext context) {
    return
        Scaffold(
            backgroundColor: Colors.white,
            appBar: PreferredSize(
                preferredSize: Size.fromHeight(55),
                child: AppBar(
                  elevation: 0.0,
                  centerTitle: true,
                  title: _getHeaderLayout(),
                  automaticallyImplyLeading: false,
                  backgroundColor: Colors.transparent,
                )),
            body:
        Container(
            child: Stack(
              children: [
                // _getHeaderLayout(),
                Container(
                    color: Colors.white,
                    margin: EdgeInsets.only(bottom: 20),
                    child: EasyRefresh(
                        emptyWidget: PageFeedBack(
                          loading: loading,
                          error: error,
                          empty: _commentListModel.isEmpty,
                          errorMsg: errorMsg,
                          onErrorTap: () =>
                              _easyRefreshController.callRefresh(),
                          onEmptyTap: () =>
                              _easyRefreshController.callRefresh(),
                        ).build(),
                        header: null,
                        footer: ClassicalFooter(),
                        controller: _easyRefreshController,
                        enableControlFinishRefresh: true,
                        enableControlFinishLoad: true,
                        topBouncing: false,
                        onRefresh: null,
                        onLoad: _commentListModel.isEmpty ? null : _onLoad,
                        child: Container(
                          child: ListView.builder(
                              controller: _scrollController,
                              shrinkWrap: true,
                              itemCount: _commentListModel.length,
                              itemBuilder: (context, index) {
                                CommentDetailModel e = _commentListModel[index];
                                return _getItemComment(e, index);
                              }),
                          padding: EdgeInsets.symmetric(
                              horizontal: 10, vertical: 20),
                        ))),
                _getBottomLayout(),
              ],
            )));
  }

  //头部布局
  _getHeaderLayout() {
    return Container(
      height: 40,
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(15), topRight: Radius.circular(15))),
      child: Stack(
        alignment: Alignment.center,
        children: [
          Positioned(
            bottom: 10,
            child: Text(
              '${momentDetailData.commentCount.toString()}条评论',
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
            ),
          ),
          Positioned(
              top: 10,
              right: 10,
              child: InkWell(
                  onTap: () {
                    Get.back();
                  },
                  child: Image.asset(
                    'assets/images/common/cross.webp',
                    color: Colors.grey,
                    width: 20,
                    height: 20,
                  )))
        ],
      ),
    );
  }

  //获取评论
  _getItemComment(CommentDetailModel e, int index) {
    return InkWell(
        onLongPress: () async {
          Map<String, dynamic> localuserLogin =
              await SPUtil.getObject('userLogin');
          if (localuserLogin['userId'] == e.userId) {
            return showModalBottomSheet<int>(
                isScrollControlled: false,
                context: context,
                shape: RoundedRectangleBorder(
                  borderRadius: const BorderRadius.only(
                    topLeft: Radius.circular(10),
                    topRight: Radius.circular(10),
                  ),
                ),
                builder: (BuildContext context) {
                  return Container(
                    constraints: BoxConstraints(minHeight: 60, maxHeight: 60),
                    child: ListView.builder(
                      itemBuilder: (BuildContext context, int index) {
                        return ListTile(
                            title: Text(options[index]),
                            onTap: () async {
                              if (index == 0) {
                                await CommentService.deleteComment(
                                    {"commentId": e.id});
                                setState(() {
                                  _commentListModel.removeAt(index);
                                });
                              }
                              Navigator.of(context).pop(index);
                            });
                      },
                      itemCount: options.length,
                    ),
                  );
                });
          }
        },
        child: Container(
          decoration: BoxDecoration(
              border: Border(
            bottom: BorderSide(width: .5, color: WcaoTheme.outline),
          )),
          width: screenWidth(context),
          margin: EdgeInsets.only(bottom: 15),
          padding: EdgeInsets.only(bottom: 15),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                width: 30,
                height: 30,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(15),
                  child:
                      CgqUtils.imageCache(e.userAvatarUrl, fit: BoxFit.cover),
                ),
              ),
              SizedBox(
                width: 10,
              ),
              Expanded(
                  child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    e.userName,
                    style: TextStyle(
                        color: Colors.black,
                        fontWeight: FontWeight.bold,
                        fontSize: 14),
                  ),
                  SizedBox(
                    height: 3,
                  ),
                  Text(getDateTime(e.createTime),
                      style: TextStyle(color: Colors.grey[400], fontSize: 10)),
                  SizedBox(
                    height: 5,
                  ),
                  InkWell(
                      onTap: () {
                        if (parentComment == null) {
                          setState(() {
                            parentComment = e;
                          });
                          return;
                        }
                        if (e.id == parentComment.id) {
                          setState(() {
                            parentComment = null;
                          });
                        } else {
                          setState(() {
                            parentComment = e;
                          });
                        }
                      },
                      child: CommentParse(
                        e.content,
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.black,
                        ),
                      )),
                  SizedBox(
                    height: 5,
                  ),
                  // SizedBox(
                  //   width: 5,
                  // ),
                  e.replyCount != null
                      ? InkWell(
                          child: Text(
                            e.replyCount.toString() + '回复',
                            style: TextStyle(
                                fontSize: 12,
                                fontWeight: FontWeight.bold,
                                color: Colors.blueAccent),
                          ),
                          onTap: () {
                            Get.to(CommentDetailPage(
                                momentId: momentDetailData.id,
                                commentId: e.id));
                          },
                        )
                      : Container(),
                ],
              )),
              SizedBox(
                width: 10,
              ),
              Column(
                children: [
                  LikeButton(
                      isLiked: e.hasLiked,
                      onTap: (isLiked) {
                        return onTapLikeButton(!isLiked, index);
                      },
                      size: 20,
                      circleColor: CircleColor(
                          start: ColorRes.color_3, end: ColorRes.color_3),
                      likeBuilder: (isLike) {
                        return isLike == true
                            ? Image.asset('assets/images/common/red_heart.webp')
                            : Icon(
                                Icons.favorite_border_outlined,
                                size: 20,
                                color: WcaoTheme.secondary,
                              );
                      },
                      bubblesColor: const BubblesColor(
                        dotPrimaryColor: ColorRes.color_3,
                        dotSecondaryColor: ColorRes.color_3,
                        dotThirdColor: ColorRes.color_3,
                        dotLastColor: ColorRes.color_3,
                      )),
                  Text(
                    e.likeCount.toString(),
                    style: TextStyle(fontSize: 12, color: Colors.grey),
                  ),
                ],
              ),
            ],
          ),
        ));
  }

  Future<bool> onTapLikeButton(bool isLiked, int index) async {
    _commentListModel[index].hasLiked = isLiked;
    if (isLiked) {
      _commentListModel[index].likeCount++;
    } else {
      _commentListModel[index].likeCount--;
    }
    Map<String, dynamic> data = {
      "targetId": _commentListModel[index].id,
      "targetType": 'COMMENT',
    };
    if (isLiked) {
      await OperationServiece.like(data);
    } else {
      await OperationServiece.cancelLike(data);
    }
    setState(() {
      _commentListModel = _commentListModel;
    });
    return isLiked;
  }

  publishComment() async {
    EasyLoading.show(status: '发送中...');
    try {
      setState(() {
        disabledPublish = false;
      });
      Map<String, dynamic> data = {
        "momentId": momentDetailData.id,
        "content": _commentEditController.text,
        "parentId": parentComment != null ? parentComment.id : 0,
        "replyToId": 0
      };
      Map<String, dynamic> result = await CommentService.publishComment(data);
      CommentDetailModel commentDetail;
      if (parentComment == null) {
        Map<String, dynamic> param = {
          "commentId": result['body'],
        };
        Map<String, dynamic> commentResult =
            await CommentService.getCommentDetail(param);
        commentDetail = CommentDetailModel.fromJson(commentResult['body']);
      }
      if (parentComment != null) {
        for (int i = 0; i < _commentListModel.length; i++) {
          if (_commentListModel[i].id == parentComment.id) {
            if (_commentListModel[i].replyCount == null) {
              _commentListModel[i].replyCount = 1;
            } else {
              _commentListModel[i].replyCount++;
            }
          }
        }
        setState(() {
          _commentListModel = _commentListModel;
        });
      } else {
        setState(() {
          _commentListModel.insert(0, commentDetail);
        });
      }
      setState(() {
        momentDetailData.commentCount++;
        parentComment = null;
        _commentEditController.text = "";
        disabledPublish = true;
        _focusNode.unfocus();
      });
      ToastUtils.showToast("发送成功");
      EasyLoading.dismiss(animation: true);
    } catch (e) {
      setState(() {
        disabledPublish = true;
      });
      EasyLoading.showError(e['retdesc'] != null ? e['retdesc'] : '发送失败');
      EasyLoading.dismiss(animation: true);
    }
  }

  //展示好友
  void showBottomFriendList() {
    showModalBottomSheet(
        backgroundColor: Colors.white,
        context: context,
        isScrollControlled: true, //可滚动 解除showModalBottomSheet最大显示屏幕一半的限制
        shape: RoundedRectangleBorder(
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(10),
            topRight: Radius.circular(10),
          ),
        ),
        builder: (context) {
          return Container(
              constraints: BoxConstraints(
                  minHeight: MediaQuery.of(context).size.height -
                      kToolbarHeight, //设置最小高度（必要）
                  maxHeight: MediaQuery.of(context).size.height
                  // -
                  //     kToolbarHeight, //设置最大高度（必要）
                  ),
              child: FriendListSelectPublishIndexPage());
        });
  }

  _getBottomLayout() {
    return Positioned(
        bottom: 0,
        left: 0,
        child: Container(
          width: MediaQuery.of(context).size.width,
          height:
              isShowkeyborad || _commentEditController.text != "" ? 100 : 40,
          decoration: BoxDecoration(
            color: Colors.white,
          ),
          child: Column(
            children: [
              Divider(
                height: 1,
                color: Colors.black12,
              ),
              Expanded(
                  child: Container(
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(horizontal: 10),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                        child: Container(
                      alignment: Alignment.topLeft,
                      padding: EdgeInsets.only(left: 10, right: 10),
                      margin: EdgeInsets.only(
                          left: 10, right: 6, top: 4, bottom: 4),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(20),
                          color: Colors.grey[100]),
                      child: TextField(
                        focusNode: _focusNode,
                        controller: _commentEditController,
                        cursorColor: Colors.redAccent,
                        keyboardType: TextInputType.multiline,
                        maxLines:
                            isShowkeyborad || _commentEditController.text != ""
                                ? 20
                                : 1,
                        minLines: 1,
                        style: TextStyle(color: Colors.black, fontSize: 11),
                        decoration: InputDecoration(
                            border: InputBorder.none,
                            hintText: parentComment != null
                                ? '回复' + parentComment.userName + '：'
                                : '写评论...',
                            hintStyle: TextStyle(color: Colors.grey[600])),
                      ),
                    )),
                    InkWell(
                      child: Container(
                        margin: EdgeInsets.only(left: 10),
                        alignment: Alignment.center,
                        child: Image.asset(
                          'assets/images/icons/publish_at.png',
                          width: 20,
                          height: 20,
                        ),
                      ),
                      onTap: showBottomFriendList,
                    ),
                    Container(
                        height: 30,
                        width: 60,
                        margin: EdgeInsets.only(left: 10, right: 10),
                        alignment: Alignment.center,
                        child: ElevatedButton(
                            style: ButtonStyle(
                                shape: MaterialStateProperty.all(
                                    RoundedRectangleBorder(
                                        borderRadius:
                                            BorderRadius.circular(20))),
                                backgroundColor: MaterialStateProperty.all(
                                  Colors.redAccent,
                                )),
                            onPressed: disabledPublish ? publishComment : null,
                            child: const Center(
                              child: Text(
                                '发送',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 12,
                                    fontWeight: FontWeight.w500),
                              ),
                            ))),
                  ],
                ),
              ))
            ],
          ),
        ));
  }
}
